package com.zifeng.rocketmq;

import com.alibaba.fastjson.JSON;
import com.zifeng.constant.RedisConstants;
import com.zifeng.pojo.Block;
import com.zifeng.pojo.Order;
import com.zifeng.utils.PowAlgorithm;
import com.zifeng.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.zifeng.constant.RedisConstants.BLOCK_ORDER_PREFIX;

@Slf4j
@Component
@RocketMQMessageListener(topic = "order-transaction-topic", consumerGroup = "block-consumer-transaction-group")
public class TransactionMessageListener implements RocketMQListener<String> {

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private PowAlgorithm powAlgorithm;

    @Override
    public void onMessage(String message) {

        log.info("接收到rocketmq事务消息:{}", message);
        Order order = JSON.parseObject(message, Order.class);
        // 检查订单是否已存在，做消息消费的幂等处理
        String orderKey = BLOCK_ORDER_PREFIX + order.getId();
        String isExist = redisUtils.get(orderKey);
        if (isExist != null) {
            log.info("订单已存在，订单ID: {}", order.getId());
            return;
        }
        Block block = powAlgorithm.mine(order);
        if (block == null) {
            log.error("挖矿失败，订单ID: {}", order.getId());
            // 通过抛异常来使得RocketMQ重新push消息
            throw new RuntimeException(new RuntimeException("挖矿失败，订单ID: " + order.getId()));
        }
        log.info("创建区块成功，block: {}", block);
        redisUtils.set(orderKey, "1", RedisConstants.BLOCK_ORDER_TTL, RedisConstants.TTL_TIME_UNIT);
    }
}

